package it.sd.wdc.spider.repository.template;


import java.io.InputStream;
import java.io.StringReader;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

public class TemplateParser {

	public SpiderNodeTemplate parse(InputStream file) throws Exception {
		
		SAXParserFactory spf = SAXParserFactory.newInstance(); 
		spf.setValidating(false);
		
		SAXParser saxParser = spf.newSAXParser(); 
		// create an XML reader
		XMLReader reader = saxParser.getXMLReader();
		// set handler
		TemplateParserHandler handler = new TemplateParserHandler();
		reader.setContentHandler(handler);
		// call parse on an input source
		reader.parse(new InputSource(file));
		
		return handler.getNodeTemplate();
	}

	public SpiderNodeTemplate parse(String xml) throws Exception {
		
		SAXParserFactory spf = SAXParserFactory.newInstance(); 
		spf.setValidating(false);
		
		SAXParser saxParser = spf.newSAXParser(); 
		// create an XML reader
		XMLReader reader = saxParser.getXMLReader();
		// set handler
		TemplateParserHandler handler = new TemplateParserHandler();
		reader.setContentHandler(handler);
		// call parse on an input source
		reader.parse(new InputSource(new StringReader(xml)));
		
		return handler.getNodeTemplate();
	}

}
